package com.akk.module.hkpay.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.StringWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.UUID;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import org.apache.commons.codec.digest.DigestUtils;

public class IdValidateClient {

	private static final String NO = "99999999";
	private static final String PASSWORD = "1a861edc704121753369894d7afc9596";
	private static final String URL = "http://113.108.195.242:25166/InterfaceChangeServers/toMain.do";// 251

	public static void main(String[] args) {
		String json = createJsonS1055();
		try {
			URLPost(URL, json);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private static String createJsonS1055() {
		Map<String, String> appHead = new HashMap<String, String>();
		appHead.put("Version", "100");
		appHead.put("TransType", "S1050");
		appHead.put("SerialNo", UUID.randomUUID().toString().replace("-", ""));
		appHead.put("DataTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
		Map<String, String> appBody = new HashMap<String, String>();
		appBody.put("institutionNo", NO);
		appBody.put("merName", "爱卡卡极速收款商户-李正");
		appBody.put("merNameShort","极速收款-李正");
		appBody.put("merAddress","四川省成都市");
		appBody.put("merLegalName","李正");
		appBody.put("merLegalNo","511921199508216738");
		appBody.put("merLegalMobilePhone","17761265912");
		appBody.put("posAreaCode","2222");
		appBody.put("mbiBankNo","304651015799");
		appBody.put("mbiBankName","华夏银行");
		appBody.put("mbiAccountUser","李正");
		appBody.put("mbiAccountNo","6259691125122144");
		appBody.put("mbiType","对私");
		appBody.put("busiNo","0311,789");
		appBody.put("rateId","5402,5403");
		appBody.put("extMerNo","7de0a5aa9259489ab916262e97a9d41d");
		appBody.put("liquidateModle","1");
		appBody.put("sign", "empty");
		Map<String, Object> appMap = new HashMap<String, Object>();
		appMap.put("AppHead", appHead);
		appMap.put("AppBody", appBody);
		String json = beanToJson(appMap);
		String[] nos = {"sign","mbiType","extMerNo","liquidateModle","defaultWalletAccount"};
		String url = HkUtils.createSortUrl(json,nos);
		url += PASSWORD;
		String signByCustomer = DigestUtils.md5Hex("busiNo=0311,789&institutionNo=99999999&liquidateModle=1&mbiAccountNo=6259691125122144&mbiAccountUser=李正&mbiBankName=华夏银行&mbiBankNo=304651015799&merAddress=四川省成都市&merLegalMobilePhone=17761265912&merLegalName=李正&merLegalNo=511921199508216738&merName=爱卡卡极速收款商户-李正&merNameShort=极速收款-李正&posAreaCode=2222&rateId=5402,5403&key=1a861edc704121753369894d7afc9596").toUpperCase();
		appBody.put("sign", signByCustomer);
		json = beanToJson(appMap);
		System.out.println(json);
		return json;
	}

	@SuppressWarnings("unchecked")
//	public static String createSortUrl(String json) {
//		StringBuilder sb = new StringBuilder();
//		try {
//			ObjectMapper objectMapper = new ObjectMapper();
//			Map<String, Object> maps = objectMapper.readValue(json, Map.class);
//			Map<String, Object> appBody = (Map<String, Object>) maps.get("AppBody");
//			Set<String> set = appBody.keySet();
//
//			// 删除不参与签名校验的字段
//			appBody.remove("mbiType");
//			appBody.remove("extMerNo");
//
//			// 排序
//			Set<String> sortSet = new TreeSet<String>();
//			sortSet.addAll(set);
//
//			// 删除sign
//			sortSet.remove("sign");
//
//			// 构造url
//			Iterator<String> it = sortSet.iterator();
//			while (it.hasNext()) {
//				String key = it.next();
//				Object value = appBody.get(key);
//				sb.append("&").append(key).append("=").append(value);
//			}
//			sb.append("&key=");
//		} catch (Exception e) {
//			e.printStackTrace();
//			sb.append("&");
//		}
//		return sb.substring(1);
//	}

	public static String beanToJson(Object bean) {
		return new Gson().toJson(bean);
	}

	public static String URLPost(String ur, String str) throws IOException {
		System.out.println("开始请求....");
		URL url = new URL(ur);
		URLConnection rulConnection = url.openConnection();
		// urlConnection对象实际上是根据URL的请求协议(此处是http)生成的URLConnection类的子类HttpURLConnection,故此处最好将其转化为HttpURLConnection类型的对象,以便用到
		HttpURLConnection httpUrlConnection = (HttpURLConnection) rulConnection;
		// 设置是否向httpUrlConnection输出，因为这个是post请求，参数要放在http正文内，因此需要设为true,
		// 默认情况下是false;
		httpUrlConnection.setDoOutput(true);
		// 设置是否从httpUrlConnection读入，默认情况下是true;
		httpUrlConnection.setDoInput(true);
		// Post 请求不能使用缓存
		httpUrlConnection.setUseCaches(false);
		// 设定传送的内容类型是可序列化的java对象
		// (如果不设此项,在传送序列化对象时,当WEB服务默认的不是这种类型时可能抛java.io.EOFException)
		httpUrlConnection.setRequestProperty("Content-Type", "application/soap+xml; charset=UTF-8");
		// 设置连接主机超时（单位：毫秒） ,读取数据连接
		httpUrlConnection.setConnectTimeout(8000);
		httpUrlConnection.setReadTimeout(100000);
		// 设定请求的方法为"POST"，默认是GET
		httpUrlConnection.setRequestMethod("POST");
		BufferedWriter bout = new BufferedWriter(new OutputStreamWriter(httpUrlConnection.getOutputStream(), "UTF-8"));
		// 开始发送字符串
		// String s = new String(str.getBytes(),"UTF-8");
		String s = str;
		bout.write(s);
		// 刷新对象输出流，将任何字节都写入潜在的流中（些处为ObjectOutputStream）
		bout.flush();
		// 关闭流对象。此时，不能再向对象输出流写入任何数据，先前写入的数据存在于内存缓冲区中,
		// 在调用下边的getInputStream()函数时才把准备好的http请求正式发送到服务器
		bout.close();

		int response = httpUrlConnection.getResponseCode();
		System.out.println("代码：");
		System.out.println(response);
		StringBuffer result = new StringBuffer();
		// 返回200说明已经请求成功
		switch (response) {
		case 200:
			try {
				InputStream inStrm = httpUrlConnection.getInputStream();
				Reader reader = null;
				BufferedReader bufferedReader = null;
				try {
					reader = new InputStreamReader(inStrm, "UTF-8");
					bufferedReader = new BufferedReader(reader);
					String line = null;
					while ((line = bufferedReader.readLine()) != null) {
						result.append(line);
					}
					System.out.println("内容：");
					System.out.println(result);
				} catch (Exception e) {
					e.printStackTrace();
				}
			} catch (Exception e) {
				System.out.println("出现异常!");
			}
		}
		return result.toString();
	}

}
